#pragma once

#include <sys/epoll.h>
#include <cstring>
#include "Log.hpp"
#include "Err.hpp"

static const int defaultfd = -1;
static const int size = 128;

class Epoller
{
public:
    Epoller(int epfd = defaultfd)
        : _epfd(epfd)
    {
    }

    void Create()
    {
        _epfd = epoll_create(size);
        if (_epfd < 0)
        {
            logMessage(FATAL, "epoll create failed! errno: %d, err_msg: %s", errno, strerror(errno));
            exit(CREATE_EPOLL_ERR);
        }
    }

    bool AddEvent(int sockfd, const uint32_t events)
    {
        struct epoll_event ev;
        ev.events = events;
        ev.data.fd = sockfd;

        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, sockfd, &ev);
        return n == 0;
    }

    int Wait(struct epoll_event *revs, int maxnum, int timeout)
    {
        int n = epoll_wait(_epfd, revs, maxnum, timeout);
        return n;
    }

    bool Control(int sock, uint32_t events, int opt)
    {
        int ret = 0;
        // 其实这里只写一个epoll_ctl()就可以，因为DEL是不设置对事件的关心的
        if (opt == EPOLL_CTL_MOD)
        {
            struct epoll_event ev;
            ev.data.fd = sock;
            ev.events = events;
            ret = epoll_ctl(_epfd, opt, sock, &ev);
        }
        else if (opt == EPOLL_CTL_DEL)
        {
            ret = epoll_ctl(_epfd, opt, sock, nullptr);
        }
        else
        {
            ret = -1;
        }

        return ret == 0;
    }

    void CloseFd()
    {
        if (_epfd != defaultfd)
            close(_epfd);
    }

    ~Epoller()
    {
        CloseFd();
    }

private:
    int _epfd;
};